package belf.migrate.api.util;

import belf.migrate.core.util.ConfigUtil;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Properties;
import java.io.InputStream;
import java.io.FileInputStream;

public class EngineConf {
    private static final EngineConf instance = new EngineConf();

    private final Properties conf;

    private EngineConf() {
        String belfConfFile = ConfigUtil.getConfigDir() + File.separator + "belf.properties";
        conf = new Properties();
        try {
            InputStream inputStream = null;
            File file = new File(belfConfFile);
            if (file.exists()) {
                inputStream = new FileInputStream(belfConfFile);
                System.out.println(String.format("load belf.properties from %s.", belfConfFile));
            } else {
                inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("belf.properties");
                System.out.println("load belf.properties from classpath.");
            }
            conf.load(inputStream);
            System.out.println("load belf.properties successfully.");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static EngineConf getInstance() {
        return instance;
    }

    public Properties getConf() {
        return conf;
    }

    public String getString(String key) {
        return conf.getProperty(key);
    }

    public String getString(String key, String defaultValue) {
        if (conf.containsKey(key)) {
            return conf.getProperty(key);
        } else {
            return defaultValue;
        }
    }

    public int getInt(String key) {
        return Integer.parseInt(conf.getProperty(key));
    }

    public int getInt(String key, int defaultValue) {
        if (conf.containsKey(key)) {
            return Integer.parseInt(conf.getProperty(key).trim());
        } else {
            return defaultValue;
        }
    }

    public long getLong(String key) {
        return Long.parseLong(conf.getProperty(key));
    }

    public long getLong(String key, long defaultValue) {
        if (conf.containsKey(key)) {
            return Long.parseLong(conf.getProperty(key));
        } else {
            return defaultValue;
        }
    }

    public boolean getBoolean(String key) {
        return Boolean.parseBoolean(conf.getProperty(key));
    }

    public boolean getBoolean(String key, boolean defaultValue) {
        if (conf.containsKey(key)) {
            return Boolean.parseBoolean(conf.getProperty(key));
        } else {
            return defaultValue;
        }
    }

    public float getFloat(String key) {
        return Float.parseFloat(conf.getProperty(key));
    }

    public float getFloat(String key, float defaultValue) {
        if (conf.containsKey(key)) {
            return Float.parseFloat(conf.getProperty(key));
        } else {
            return defaultValue;
        }
    }
}
